package pacs_server

import (
	"gitee.com/uni-minds/bridge-pacs/dcm4chee"
	"time"
)

// ProcessPacsDcm4cheeServer 拉取PACS数据
//
// 步进step，协进workers
func (pi *PacsServer) ProcessPacsDcm4cheeServer(step, workers int, quickMode bool) (stat ImportDetails) {
	connector := dcm4chee.NewConnector(pi.ServerHost, pi.ServerAETs)
	count := connector.CountStudies()
	chanFreeWorker := make(chan int, workers*2)
	pi.Log("sync start, total studies:", count)

	syncWorkers := make([]*SyncWorker, workers)

	// 初始化Worker
	for i := 0; i < workers; i++ {
		worker := NewSyncWorker(pi, i, pi.logger != nil, chanFreeWorker)
		if quickMode {
			worker.UseQuickMode()
		}
		go worker.Start()
		syncWorkers[i] = worker
	}
	// 循环投喂
	for i := 0; i < count; i += step {
		select {
		case idx := <-chanFreeWorker:
			pi.Logf("Sync progress: %d%%", i*100/count)
			syncWorkers[idx].Feed(i, step)
		}
	}
	// 等待Worker初始化
	pi.Log("waiting for workers initialize")
	time.Sleep(100 * time.Millisecond)
	// 等待Worker结束
	for flagBusy := true; flagBusy; {
		flagBusy = false
		for _, worker := range syncWorkers {
			//pi.Log("busy:", worker.IsBusy())
			flagBusy = flagBusy || worker.IsBusy()
		}

		//pi.Log("busy total:", flagBusy)
	}
	// 全部Worker结束
	stat = ImportDetails{
		CountStudies:  0,
		CountSeries:   0,
		CountInstance: 0,
		ImportStudies: nil,
	}

	for _, worker := range syncWorkers {
		status := worker.ClearStatus()
		stat.ImportStudies = append(stat.ImportStudies, status.ImportStudies...)
		stat.CountStudies += status.CountStudies
		stat.CountSeries += status.CountSeries
		stat.CountInstance += status.CountInstance
		worker.Stop()
	}

	pi.Logf("sync finish, import %d studies, %d series, %d instances.", stat.CountStudies, stat.CountSeries, stat.CountInstance)
	return stat
}
